package singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author liouwb
 * 单例模式 静态内部类
 */
public class SingletonInnerTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // 单例静态内部类
        SingletonInner inner = SingletonInner.getInstance();
        SingletonInner inner1 = SingletonInner.getInstance();

        // 通过反射实例
        Class<SingletonInner> lazyClass = SingletonInner.class;
        Constructor<SingletonInner> constructor = lazyClass.getDeclaredConstructor();

        constructor.setAccessible(true);
        SingletonInner inner2 = constructor.newInstance();

        // 验证单例是否全局只有一个实例
        System.out.println("正常获取的实例比较：" + (inner == inner1));
        // 反射获取与正常获取对比
        System.out.println("正常获取的实例比较：" + (inner == inner2));

        // 输出相应对象
        System.out.println("inner ：" + inner);
        System.out.println("inner1：" + inner1);
        System.out.println("inner2：" + inner2);
    }

    /**
     * 单例静态内部类
     */
    static class SingletonInner {
        private SingletonInner() {
        }

        private static class SingletonHoler {
            private static SingletonInner INSTANCE = new SingletonInner();
        }

        public static final SingletonInner getInstance() {
            return SingletonHoler.INSTANCE;
        }

    }
}
